package br.com.simora.robo;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;

import javax.annotation.PostConstruct;

import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Result;
import br.com.simora.controller.BasicController;

@Controller
public class RoboController extends BasicController {

	public RoboController(Result result, ResourceBundle bundle) {
    	this.result = result;
		this.bundle = bundle;
	}
	
	 public RoboController(){}
	    
	@PostConstruct
    public void init(){
        injetaUsuario();
    }
	
	@Path(value = "/" + ROBO)
    @Get
    public void robo() {
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
		Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
		List<String> nomes = new ArrayList<String>();
		for(Thread t : threadArray){
			if(t.getName().contains("weld-worker")){
				t.getClass();
			}
			nomes.add(t.getName());
		}
		Thread currentThread = Thread.currentThread();
	    ThreadGroup threadGroup = getRootThreadGroup(currentThread);
	    int allActiveThreads = threadGroup.activeCount();
	    Thread[] allThreads = new Thread[allActiveThreads];
	    threadGroup.enumerate(allThreads);
	    ThreadMXBean tbean;
	    tbean = ManagementFactory.getThreadMXBean();
	    long[] IDs=tbean.getAllThreadIds();

	    for (int i = 0; i < allThreads.length; i++) {
	        Thread thread = allThreads[i];
	        long id = thread.getId();
	        System.out.println(id + " - " + thread.getName());
	    }
		result.include("listaRobos", nomes);
    }
	
	private static ThreadGroup getRootThreadGroup(Thread thread) {
	    ThreadGroup rootGroup = thread.getThreadGroup();
	    while (true) {
	        ThreadGroup parentGroup = rootGroup.getParent();
	        if (parentGroup == null) {
	            break;
	        }
	        rootGroup = parentGroup;
	    }
	    return rootGroup;
	}

	@Override
	protected void redirect() {
		// TODO Auto-generated method stub
		
	}
}
